/**
 * Copyright (c) 2004-2006, Martin Fiedler.  All rights reserved.
 * Copyright (c) 2012, Ken Anderson.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR 
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **/
 
#include "common.h"
#include "input.h"
#include "cavlc.h"


code_table *init_code_table(code_table_item *items) {
  code_table *res=malloc(sizeof(code_table));
  code_table_item *pos;
  int count=0;
  for(pos=items; pos && pos->code!=0xFFFFFFFF; ++pos) ++count;
  res->items=items;
  res->count=count;
  return res;
}

int get_code(code_table *table) {
  unsigned int code=input_peek_bits(24)<<8;
  int min=0, max=table->count;
  while(max-min>1) {
    int mid=(min+max)>>1;
    if(code>=table->items[mid].code) min=mid; else max=mid;
  }
  input_step_bits(table->items[min].bits);
  return table->items[min].data;
}


int get_unsigned_exp_golomb() {
  int exp;
  for(exp=0; !input_get_one_bit(); ++exp);
  if(exp) return (1<<exp)-1+input_get_bits(exp);
     else return 0;
}

int get_signed_exp_golomb() {
  int code=get_unsigned_exp_golomb();
  return (code&1) ? (code+1)>>1 : -(code>>1);
}
